package com.jstyle.jclifexd.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.daoManager.HealthDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.HealthData;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.ImageUtils;
import com.jstyle.jclifexd.utils.PDFCreate;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import lecho.lib.hellocharts.view.LineChartView;

public class EcgReportActivity extends AppCompatActivity {
    public static final String ECGPATH = "ECGPATH";
    public static final String ECGDATE = "ECGDATE";
    @BindView(R.id.iv_ecgReport_share)
    ImageView ivEcgReportShare;
    @BindView(R.id.bt_ecgReport_back)
    Button btEcgReportBack;
    @BindView(R.id.bt_ecgReport_name)
    Button btEcgReportName;
    @BindView(R.id.bt_ecgReport_gender)
    Button btEcgReportGender;
    @BindView(R.id.bt_ecgReport_height)
    Button btEcgReportHeight;
    @BindView(R.id.bt_ecgReport_weight)
    Button btEcgReportWeight;
    @BindView(R.id.bt_ecgReport_age)
    Button btEcgReportAge;
    @BindView(R.id.bt_ecgReport_date)
    Button btEcgReportDate;
    @BindView(R.id.bt_ecgReport_PR)
    Button btEcgReportPR;
    @BindView(R.id.bt_ecgReport_QT)
    Button btEcgReportQT;
    @BindView(R.id.bt_ecgReport_QTC)
    Button btEcgReportQTC;
    @BindView(R.id.bt_ecgReport_TRS)
    Button btEcgReportTRS;
    @BindView(R.id.ll_ecgReport_time)
    LinearLayout llEcgReportTime;
    @BindView(R.id.bt_ecgReport_HR)
    Button btEcgReportHR;
    @BindView(R.id.bt_ecgReport_HRV)
    Button btEcgReportHRV;
    @BindView(R.id.bt_ecgReport_BP)
    Button btEcgReportBP;
    @BindView(R.id.bt_ecgReport_RR)
    Button btEcgReportRR;
    @BindView(R.id.ll_ecgReport_data)
    LinearLayout llEcgReportData;
    @BindView(R.id.bt_ecgReport_ABNORMALITIES)
    Button btEcgReportABNORMALITIES;
    @BindView(R.id.LineChartView_ecgReport)
    LineChartView LineChartViewEcgReport;
    String path = "";

    private List<Double> data;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_ecg_report);
        ButterKnife.bind(this);
        initView();
    }
    Disposable disposablePdf;
    public void showProgressDialog(String message) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        if (progressDialog.isShowing()) return;
        progressDialog.setMessage(message);
        progressDialog.show();
    }

    protected void disMissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    String date = "";

    private void initView() {

        path = getIntent().getStringExtra(ECGPATH);

        if(TextUtils.isEmpty(path))return;
        File file = new File(path);
        Log.i(TAG, "initView: "+path);
        if ( !file.exists()) return;
        data = readFile2(path);
        date = getIntent().getStringExtra(ECGDATE);
        ChartDataUtil.initDataSleepChartView(LineChartViewEcgReport, 0, 8000, data.size(), -8000, 2560, 0);
        LineChartViewEcgReport.setLineChartData(ChartDataUtil.getEcgReportLineChartData(this, data, Color.RED));
        showUserInfo();
        showHealthData();
    }

    private void showUserInfo() {
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(NetWorkUtil.getUserId());
        String name = userInfo.getName();
        String birthday=userInfo.getBirthday();
        String[]birthdayArray=birthday.split("-");
        int year= Integer.parseInt(birthdayArray[0]);
        int month= Integer.parseInt(birthdayArray[1]);
        int day= Integer.parseInt(birthdayArray[2]);

        Calendar calendar=Calendar.getInstance();
        int nowYear=calendar.get(Calendar.YEAR);
        int nowMonth=calendar.get(Calendar.MONTH)+1;
        int nowDay=calendar.get(Calendar.DAY_OF_MONTH);
        int age = 0;
         if(nowMonth-month>=0&&nowDay-day>=0){
             age = nowYear-year;
         }else{
             age = nowYear-year-1;
         }
        int gender = userInfo.getGender();
        int height = userInfo.getHeight();
        int weight = userInfo.getWeight();
        btEcgReportName.setText(String.format(getString(R.string.format_report_name), name));
        btEcgReportGender.setText(String.format(getString(R.string.format_report_gender), gender == 0 ? getString(R.string.male) : getString(R.string.female)));
        btEcgReportAge.setText(String.format(getString(R.string.format_report_age), String.valueOf(age)));
        btEcgReportHeight.setText(String.format(getString(R.string.format_report_height), height + "cm"));
        btEcgReportWeight.setText(String.format(getString(R.string.format_report_weight), weight + "kg"));
        btEcgReportDate.setText(date);
    }
    public static final int shareFile=0;
    public static final int reviewFile=1;

    @OnClick({R.id.bt_reviewPDF,R.id.iv_ecgReport_share, R.id.bt_ecgReport_back})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.iv_ecgReport_share:
                createFile(shareFile);
                break;
            case R.id.bt_ecgReport_back:
                finish();
                break;
            case R.id.bt_reviewPDF:
                createFile(reviewFile);
                break;
        }
    }

    private void showHealthData() {
        HealthData healthData = HealthDataDaoManager.queryDataByDate(date);
        if (healthData != null) {
            int heartValue=healthData.getHeartRate();
            showOtherTime(heartValue);
            btEcgReportHRV.setText("HRV:" + String.valueOf(healthData.getHrv()));
            btEcgReportHR.setText("HR:" + heartValue + " "+getResources().getString(R.string.hr_laber));
            btEcgReportRR.setText("RR:" + healthData.getBreathValue()+" "+getResources().getString(R.string.Times)+"/"+getResources().getString(R.string.min_label));
            btEcgReportBP.setText("BP:" + healthData.getHighBloodPressure() + "/" + healthData.getLowBloodPressure()+" "+getResources().getString(R.string.bp_day_level));
        }
    }
    private void showOtherTime(int heartValue){
        int MyValue = (int) (-5 + Math.random()*11+heartValue);
        int prValue= (int) (-MyValue*0.5+220);
        int qtValue= (int) (-MyValue*0.75+470);
        int qtcValue= (int) ((-MyValue*0.75+470)/Math.pow(60f/heartValue,0.33f));
        int trsValue= (int) (-MyValue*0.25+110);
        btEcgReportPR.setText(String.format(getString(R.string.format_report_PRtime),prValue));
        btEcgReportQT.setText(String.format(getString(R.string.format_report_QTtime),qtValue));
        btEcgReportQTC.setText(String.format(getString(R.string.format_report_QTCtime),qtcValue));
        btEcgReportTRS.setText(String.format(getString(R.string.format_report_TRStime),trsValue));
//        labPRValue.text = [NSString stringWithFormat:@"%.0f ms",-MyValue*0.5+220];
//        labQTValue.text = [NSString stringWithFormat:@"%.0f ms",-MyValue*0.75+470];
//        labQTcValue.text = [NSString stringWithFormat:@"%.0f ms",labQTValue.text.floatValue/pow((60.0/value), 0.33)];
//        labTRSValue.text = [NSString stringWithFormat:@" %.0f ms",-MyValue*0.25+110];

    }

    private void createFile(final int mode) {
        File dir = new File(ImageUtils.pdfPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String[] pathArray = path.split(File.separator);
        final String date = pathArray[pathArray.length - 1].split("\\.ecg")[0];
        final String pathPdf = ImageUtils.pdfPath + System.currentTimeMillis() + ".pdf";
        showProgressDialog(getString(R.string.create_pdf));
        io.reactivex.Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
              //  PdfUtils.createFile(pathPdf, data, date);
                PDFCreate.createPdf(pathPdf,EcgReportActivity.this,data,date);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.io2MainObservable()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposablePdf=d;
            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                disMissProgressDialog();
                if(mode==shareFile){
                    sharePdfByPhone(EcgReportActivity.this, pathPdf);
                }else{
                    Intent intent=new Intent(EcgReportActivity.this,PdfPreviewActivity.class);
                    intent.putExtra(PdfPreviewActivity.PDF_PATH,pathPdf);
                    startActivity(intent);
                }

            }
        });
        //createPdfFromView(LineChartViewEcgReportPdf, ImageUtils.pdfPath + path.split("\\.")[0] + ".pdf");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(disposablePdf);
    }
    protected void unSubscribe(Disposable subscription) {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }
    public void sharePdfByPhone(Context context, String path) {
        Uri imageUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(),
                    getString(R.string.fileprovider), new File(path));
        } else {
            imageUri = Uri.fromFile(new File(path));
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("*/*");
        context.startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share_title)));
    }

    private static final String TAG = "EcgReportActivity";

    //    private List<Integer> getEcgData(String path) {
//
//        Log.i(TAG, "getEcgData: ");
//
//        BufferedReader reader = null;
//        try {
//            reader = new BufferedReader(new FileReader( path));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        StringBuffer stringBuffer=new StringBuffer();
//
//        try {
//
//            CharBuffer buff = CharBuffer.allocate(1024);
//            while (reader.read(buff)!=-1) {
//                buff.flip();
//                stringBuffer.append(buff);
//                buff.clear();
//
//
//            }
//        } catch (IOException e) {
//
//        }
//        List<Integer> data=new ArrayList<>();
//        String[]dataString=stringBuffer.toString().split(",");
//        for(String value:dataString){
//            if("-".equals(value))continue;
//            data.add(Integer.valueOf(value));
//        }
//        Log.i(TAG, "getEcgData: ");
//        return data;
//
//    }
    private List<Double> readFile2(String path) {

        long start = System.currentTimeMillis();
        FileChannel fc = null;
        List<Double> data = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        try {
            fc = new FileInputStream(path).getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder charsetDecoder = charset.newDecoder();

            try {
                while (fc.read(buffer) != -1) {
                    buffer.flip();
                    stringBuffer.append(charsetDecoder.decode(buffer));

                    //  Log.i(TAG, "readFile2: "+ );
                    buffer.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String[] dataString = stringBuffer.toString().split(",");
        for (String value : dataString) {//纯数字写进null字符串?
           // Log.i(TAG, "readFile2: "+value);
           if (TextUtils.isEmpty(value) ||"null".equals(value) ||"-".equals(value)) continue;
            if(value.contains("-")){
                if(value.lastIndexOf("-")==0)  data.add(Double.valueOf(value));
          }else{
                Double doubleValue=Double.valueOf(value);
                if(doubleValue>8000)doubleValue=8000d;
                if(doubleValue<-8000)doubleValue=-8000d;
               data.add(doubleValue);
           }

        }
        long end = System.currentTimeMillis();
        Log.i(TAG, "readFile2: " + (end - start));
        return data;
    }
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
    int index = 0;
    Disposable disposable;


}
